<template>
	<view>
		<input type="number" v-model="formData.phone" placeholder="手机号" class="nick-name-input" :auto-blur="true">

		<view class="tips">
			为了更好的为您服务,请授权获取手机号<button size="mini" type="primary" open-type="getPhoneNumber" @getphonenumber="getPhone"
				class="phone-btn">获取手机号</button>
		</view>
		<button @click="wxlogin" class="login-btn" type="primary">登录</button>
	</view>
</template>

<script>
	import {
		getUserPhone,
		updateInfo,
		getMyInfoNoSecure,
	} from '@/api/my/my'
	import uploadFile from '@/utils/uploadFile.js'
	export default {
		data() {
			return {
				formData: {
					avatarUrl: "",
					nickname: "",
					phone:"",
				},
				avatar:''
			};
		},
		onLoad() {
			this.init()
		},
		methods: {
			async init() {
				let myInfo = await getMyInfoNoSecure()
				this.formData.avatarUrl = myInfo.imageUrl
				this.formData.nickname = myInfo.nickname
				this.formData.phone = myInfo.phone
				this.avatar = myInfo.imageUrl
			},
			chooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				this.formData.avatarUrl = avatarUrl;
			},
			blueNickname(e) {
				let nk = e.detail.value
				this.$nextTick(() => {
					this.formData.nickname = nk
				})
				// if (nk == '') {
					
				// } else {
				// 	this.formData.nickname = nk;
				// }
			},
			async getPhone(e) {
				let phone = await getUserPhone({
					code: e.detail.code
				})
				this.formData.phone = phone;
			},
			async wxlogin() {
				
				let phone = this.formData.phone
				// 验证手机号
				if (!/^1[3456789]\d{9}$/.test(phone)) {
					return uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
				}
				uni.showLoading({
					title: '登录中',
					mask: true
				});
				if(this.avatar !== this.formData.avatarUrl) {
					const {
						fileUrl: aUrl
					} = await uploadFile(this.formData.avatarUrl, 'avatar/')
					this.avatar = aUrl
				}
				updateInfo({
					"avatarUrl": this.avatar,
					"nickName": this.formData.nickname,
					"phone": phone,
				}).then(res => {
					uni.setStorageSync("userinfo", res)
					uni.showToast({
						title: '保存成功',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 300)
					
				}).catch(e => {
					uni.showToast({
						title: e.data.msg || '操作失败',
						icon:'error'
					});
				}).finally(() => {
					uni.hideLoading()
				})
			},
		}
	}
</script>

<style lang="scss">
	.avatar-wrapper {
		margin-top: 15px;
		height: 200rpx;
		width: 200rpx;
		padding: 0;
	}

	.avatar {
		display: block;
		height: 200rpx;
		width: 200rpx;
		border-radius: 8px;
	}

	.nick-name-input {
		border: 1px solid #9c9c9c;
		padding-left: 10px;
		border-radius: 5px;
		height: 40px;
		line-height: 40px;
		width: 200px;
		margin: 15px auto;
		text-align: center;
	}

	.tips {
		font-size: 12px;
		color: #5f5f5f;
		display: flex;
		align-items: center;
	}

	.login-btn {
		margin-top: 10px;
	}
</style>